package org.csu.mypetstore.api.common;


//拦截器

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;


//拦截器
@Service
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenUtil jwtUtil;




    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 放行OPTIONS请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        // 放行登录和注册接口
        if (request.getRequestURI().contains("/account/tokens")
                || request.getRequestURI().contains("/account/accounts")) {
            return true;
        }

        // 检查 Token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonResponse = objectMapper.writeValueAsString(CommonResponce.createForError(401, "令牌失效！"));
            response.getWriter().write(jsonResponse);
            return false;
        }
        token = token.replace("Bearer ", "");
        try {
            Claims claims = JwtTokenUtil.getClaimsByToken(token);
            System.out.println("claims = " + claims);
            request.setAttribute("user", claims.getSubject());
            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

    private void sendError(HttpServletResponse response, int status, String msg) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(
                new JSONObject()
                        .put("status", status)
                        .put("msg", msg)
                        .toString()
        );
        response.getWriter().flush();
    }

}



